<template>
  <!-- 操作日志 -->
  <custom-container ref="customContainerRef" :config="config" />
  <setForm ref="setFormRef" @changeList="handleQuery" />
</template>
<script lang="ts" setup>
import {
  Delete,
  View } from '@element-plus/icons-vue'
import { ref, getCurrentInstance, defineAsyncComponent, computed, reactive } from 'vue'
import { ElMessage, ElMessageBox, ElButton } from 'element-plus'
import { useI18n } from 'vue-i18n'
import { DictDirection } from '@/store/modules/dicts'
import { list, delOperlog, cleanOperlog } from '@/api/system/operationLog'

const { t } = useI18n()
const setForm = defineAsyncComponent(() => import('./components/setForm.vue'))
const // 查询参数
  queryParams = ref({
    pageNum: 1,
    pageSize: 10,
  }),
  // 选中数组
  // 非多个禁用
  multiple = ref(true),
  single = ref(false),
  //
  customContainerRef = ref(null),
  // 详细
  setFormRef = ref(null),
  {
    appContext: {
      config: {
        globalProperties: { $download },
      },
    },
  } = getCurrentInstance()
// 查询
const handleQuery = () => {
  queryParams.value.pageNum = 1
  customContainerRef.value.getList()
}
let ids = []
// 多选框选中数据
const handleSelectionChange = (rows: { [key: string]: any }[]) => {
  const rowsList = JSON.parse(JSON.stringify(rows))
  ids = rowsList.map((item) => item.operId)
  multiple.value = !rowsList.length
}
/** 删除按钮操作 */
const handleDelete = () => {
  // const rowList = JSON.parse(JSON.stringify(row))
  // const id = rowList.operId || ids
  ElMessageBox.confirm(
    `"是否确认删除日志编号为"${ ids }"的日志记录?"`,
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    },
  )
  .then(() => delOperlog(ids))
  .then((res) => {
    if (res.code === 200) {
      handleQuery()
      ElMessage.success('删除成功')
    } else {
      ElMessage.error(res.msg)
    }
  })
  .catch((error) => {
    if (error == 'cancel') {
      ElMessage.error('取消删除')
    }
  })
}
// 清空操作日志
const handleClean = () => {
  ElMessageBox.confirm('是否确认清空操作日志记录？', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
  .then(() => cleanOperlog())
  .then(res => {
    if (res.code == 200) {
      ElMessage.success('已经成功清空了操作日志')
      handleQuery()
      single.value = false
    }
  })
  .catch(error => {
    if (error == 'cancel') {
      ElMessage.info('取消删除')
    }
  })
}
// 导出操作日志
const handleExport = () => {
  $download('/system/operate/log/export', { queryParams }, `操作日志_${ new Date().getTime() }.xlsx`)
}
// 详细列表
const hanleView = (row:{[key:string]:any}) => {
  const rowList = JSON.parse(JSON.stringify(row))
  setFormRef.value.form = rowList
  setFormRef.value.open = true
}
const config = computed(() => {
  const queryField = 'system.dict.queryField.operationLog.'
  const btns = 'system.dict.btns.'
  const columns = 'system.dict.columns.operationLog.'
  const publicKey = 'public.'
  return {
    query: {
      fields: [
        {
          label: t(`${ queryField }title`),
          prop: 'title',
          option: {
            placeholder: '请输入系统模块',
          },
        },
        {
          label: t(`${ queryField }operName`),
          prop: 'operName',
          option: {
            placeholder: '请输入操作人员',
          },
        },
        {
          label: t(`${ queryField }businessType`),
          prop: 'businessType',
          type: 'select',
          option: {
            placeholder: '请输入操作类型',
            dictInfo: {
              dict: DictDirection.操作类型,
            },
          },
        },
        {
          label: t(`${ queryField }status`),
          prop: 'status',
          type: 'select',
          option: {
            placeholder: '请输入操作状态',
            dictInfo: {
              dict: DictDirection.操作状态,
            },
          },
        },
        {
          label: t(`${ queryField }dateRange`),
          prop: 'dateRange',
          type: 'datePicker',
        },
      ],
      queryParams: queryParams.value,
    },
    btns: [
      {
        title: t(`${ btns }del`),
        icon: Delete,
        type: 'danger',
        disabled: multiple.value,
        directive: [['hasPermi', ['system:client:remove']]],
        onClick: handleDelete,
      },
      {
        title: t(`${ btns }clean`),
        icon: Delete,
        type: 'danger',
        disabled: single.value,
        directive: [['hasPermi', ['system:operlog:remove']]],
        onClick: handleClean,
      },
      {
        title: t(`${ btns }export`),
        icon: Delete,
        type: 'warning',
        directive: [['hasPermi', ['system:config:export']]],
        onClick: handleExport,
      },
    ],
    table: {
      columns: [
        { type: 'selection', minWidth: '55', align: 'center' },
        {
          label: t(`${ columns }operId`),
          prop: 'operId',
          align: 'center',
          minWidth: '90',
        },
        {
          label: t(`${ columns }title`),
          prop: 'title',
          align: 'center',
          minWidth: '90',
        },
        {
          label: t(`${ columns }operatorType`),
          prop: 'operatorType',
          align: 'center',
          minWidth: '90',
          autoFormatter: {
            dict: DictDirection.操作状态,
            rowKey: 'operatorType',
          },
        },
        {
          label: t(`${ columns }requestMethod`),
          prop: 'requestMethod',
          align: 'center',
          minWidth: '90',
        },
        {
          label: t(`${ columns }operName`),
          prop: 'operName',
          align: 'center',
          minWidth: '90',
        },
        {
          label: t(`${ columns }operIp`),
          prop: 'operIp',
          align: 'center',
          minWidth: '90',
          option: {
            showOverflowTooltip: true,
          },
        },
        {
          label: t(`${ columns }businessType`),
          prop: 'businessType',
          align: 'center',
          minWidth: '90',
          autoFormatter: {
            dict: DictDirection.操作类型,
            rowKey: 'businessType',
          },
        },
        {
          label: t(`${ columns }operTime`),
          prop: 'operTime',
          align: 'center',
          minWidth: '90',
        },
        {
          label: t(`${ columns }operation`),
          prop: 'opera',
          align: 'center',
          className: 'custormFixedCol',
          fixed: 'right',
          showOverflowTooltip: false,
          render: (h, params) => {
            const buttons = [
              {
                title: t(`${ btns }detailed`),
                icon: View,
                clickFun: hanleView,
                directive: [['hasPermi', ['system:operlog:query']]],
              },
            ]
            return buttons.map((el) => h(
              ElButton,
              {
                text: true,
                type: 'primary',
                icon: el.icon,
                onClick: () => {
                  el.clickFun(params.row)
                },
              },
              {
                default: () => el.title,
              },
            ))
          },
        },
      ],
      event: {
        onSelectionChange: (rows) => {
          handleSelectionChange(rows)
        },
      },
    },
    api: list,
    customKey: 'system/logManagement/operationLog',
  }
})
</script>
